package com.eamois.dao.manual.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.eamois.dao.impl.BaseDaoImpl;
import com.eamois.dao.manual.ManualEnsipDao;
import com.eamois.domain.manual.ManualEngine;
import com.eamois.domain.manual.ManualEnsip;

public class ManualEnsipDaoImpl extends BaseDaoImpl<ManualEnsip>
		implements ManualEnsipDao {
	@SuppressWarnings("unchecked")
	public Collection<ManualEnsip> findEnsipByParent(
			final ManualEnsip ensip) {
		// TODO Auto-generated method stub
		return (Collection<ManualEnsip>) 
				this.getHibernateTemplate().execute(new HibernateCallback() {

					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						Criteria criteria = session
								.createCriteria(ManualEnsip.class);
						criteria.add(Restrictions.eq("parentEnsip", ensip));
						return criteria.list();
					}
				});
	}


	@SuppressWarnings("unchecked")
	@Override
	public Collection<ManualEnsip> findEnsipByEngine(final ManualEngine manualEngine) {
		// TODO Auto-generated method stub
		return (Collection<ManualEnsip>)this.getHibernateTemplate().execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = session.createCriteria(ManualEnsip.class);
				criteria.add(Restrictions.eq("manualEngine", manualEngine));
//				criteria.add(Restrictions.isNull("parentEnsip"));
				return criteria.list();
			}
		});
	}


	@SuppressWarnings("unchecked")
	@Override
	public ManualEnsip findEnsipByNameAndEngine(final String name,final ManualEngine engine) {
		// TODO Auto-generated method stub
		return (ManualEnsip) 
				this.getHibernateTemplate().execute(new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						// TODO Auto-generated method stub
						Criteria criteria = session.createCriteria(ManualEnsip.class);
						if(name!=null)
							criteria.add(Restrictions.eq("name", name));
						if(engine!=null)
							criteria.add(Restrictions.eq("manualEngine", engine));
						ArrayList<ManualEnsip> list = (ArrayList<ManualEnsip>) criteria.list();
						if(list.size()==0){
							return null;
						}else{
							return list.get(0);
						}
					}
				});
	}

}
